package com.zis.wechat.service.impl;

import com.zis.base.impl.BaseInterImpl;
import com.zis.core.Constant;
import com.zis.core.ResponseEntity;
import com.zis.wechat.api.config.WxConstant;
import com.zis.wechat.model.Account;
import com.zis.wechat.service.IAccountInter;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Create by wangshen 2018/1/2
 */
@Service
@Transactional("txManager")
public class AccountInterImpl extends BaseInterImpl<Account> implements IAccountInter {

    @Autowired
    private SQLManager sqlManager;

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    @Override
    public String insert(Account account) throws Exception {
        int num = sqlManager.insert(account);
        if(num > 0){
            return ResponseEntity.createNormalJsonResponse(Constant.DATA_RESULT_SUCCESS);
        }
        return ResponseEntity.createErrorJsonResponse(Constant.DATA_RESULT_ERROR);
    }

    @Override
    public String update(Account account) throws Exception {
        int num = sqlManager.updateTemplateById(account);
        if(num > 0){
            return ResponseEntity.createNormalJsonResponse(Constant.DATA_RESULT_SUCCESS);
        }
        return ResponseEntity.createErrorJsonResponse(Constant.DATA_RESULT_ERROR);
    }

    @Override
    public String delete(String id) throws Exception {
        int num = sqlManager.deleteById(Account.class, id);
        if(num > 0){
            return ResponseEntity.createNormalJsonResponse(Constant.DATA_RESULT_SUCCESS);
        }
        return ResponseEntity.createErrorJsonResponse(Constant.DATA_RESULT_ERROR);
    }

    @Override
    public Account selectById(String id) throws Exception {
        return sqlManager.unique(Account.class, id);
    }

    @Override
    public List<Account> findByCondition(Account account) throws Exception {
        return sqlManager.template(account);
    }

    /**
     * 设置全部配置到redis中
     * @return
     * @throws Exception
     */
    @Override
    public String setAllToRedis() throws Exception {
        List<Account> accountList = sqlManager.all(Account.class);
        for (Account account : accountList) {
            redisTemplate.opsForHash().put(WxConstant.WECHAT_ACCOUNT_KEY, account.getAccountId(), account);
        }
        return ResponseEntity.createNormalJsonResponse("公众号信息设置成功");
    }
}
